
(function(){var homeApp = angular.module('homeApp', []);
// create angular controller
	homeApp.controller('homeController', ['$scope','$http','$sce',function($scope,$http,$sce) {
		  var messageTopic;
	      $scope.test = 0;
	      $scope.MessageId = 0;
	       $scope.check =0;
	     
	   
	      //This function is to ceck if the user has signed in
	      $scope.CheckSession = function(){
	    	  if(!$scope.test){
	    		  $.post("CheckSessionUserName",
	    				  { }
	    				).then(function(response) {
	                	
	    					if (response == "Success")
	    					{
	                			
	    					}
	    					else
	    					{
	    						window.location = '\login.html';
	            		
	    					}
	    				},
	    				
	    				    function(returnedData){
	    				         console.log(returnedData);
	    					});
	    		$scope.test = 1;
	    	  }
	      };
	      
	      
		       
	      //this function is for finding the Topic of the message
	      $scope.highlight = function(text){
	    	  if (!text || text.length == 0) return $sce.trustAsHtml(text);
	    	  
	    	  var retext = text;
	    	  var match;
	    	  var sfxStr;
	    	  var prfxStr;
	    	 
	    	  
	    	//find the place of the topic in the message
	    	  var topicStartIndex = text.indexOf('#');
	    	  var topicEndIndex   = text.indexOf(' ',topicStartIndex);
	    	  
			//find the place of the reply/mention
	    	  var mentionStartIndex = text.indexOf('@');
	    	  var mentionEndIndex   = text.indexOf(' ',mentionStartIndex);
	    	  
	    	  if((topicStartIndex != -1) || (mentionStartIndex != -1)){
	    		  if(topicStartIndex != -1){  
	    			  //highlight the topic 
	    			  prfxStr = text.substring(0,topicStartIndex);
	    			  if(topicEndIndex == -1){
	    				  match = text.substring(topicStartIndex,text.length);
	    				  retext = prfxStr + '<span class="highlight"  style="cursor: pointer;">' + match + '<\/span>';
	    			  }else{
	    				  match = text.substring(topicStartIndex,topicEndIndex);
	    				  sfxStr = text.substring(topicEndIndex, text.length);
	    				  retext = prfxStr + '<span class="highlight"  style="cursor: pointer;">' + match + '<\/span>' + sfxStr;
	    			  }
	    			  
	    			  $scope.topic = match.substring(1);
	    		  }
	    		  if(mentionStartIndex != -1){
	    			  
	    			//highlight the reply/mention
	    			  var startIndex = 0, searchStrLen = 1;
	    			  var index, indices = [];
	    			  var spaceIndex;
	    			  while ((index = retext.indexOf('@', startIndex)) > -1) {
	    				  
	    			       spaceIndex =  retext.indexOf(' ',index);
	    			       if(spaceIndex == -1){
	    			    	   if(retext.indexOf('@',index+1)> -1){
	    			    		   spaceIndex = retext.indexOf('@',index+1);
	    			    	   }else{
	    			    		   spaceIndex = retext.length;
	    			    	   }
	    			    	 
	    			    	   prfxStr = retext.substring(0,index);
	    			    	   match   = retext.substring(index,spaceIndex);
	    			    	   sfxStr  = retext.substring(spaceIndex,retext.length);

	    			    	   
	    			       }else{
	    			    	   prfxStr = retext.substring(0,index);
	    			    	   match   = retext.substring(index,spaceIndex);
	    			    	   sfxStr  = retext.substring(spaceIndex,retext.length);
	    			       }
	    			       

	    		      
	    			       
	    			       if( $scope.check == 1){
	    			    	   if(spaceIndex == retext.length){
	    			    		   retext = prfxStr + '<span class="highlight"  style="cursor: pointer;">' + match + '<\/span>';
	    			    	   }else{
	    			    		   retext = prfxStr + '<span class="highlight"  style="cursor: pointer;">' + match + '<\/span>' + sfxStr;
	    			    	   }
	    			       
	    			    	   startIndex = index + searchStrLen + 52 + match.length;
	    			       }else{
	    			    	   startIndex = index + searchStrLen;
	    			       }
	    			  }
	    		  }
	    		
	    	  return $sce.trustAsHtml(retext);
	    	}else{
	    		return $sce.trustAsHtml(text);
	    	}
	      };
	      
	      //this method is for posting a new message
			$scope.AddMessage = function(){
				$.post("PostNewMessage",
				  { Topic 	:     $scope.topic,
					Content : 	  $scope.Message }
				).then(function(response) {
					var json = JSON.parse(response);
					//alert(json["Autor"]);
					$("#postAlert").show();
					setTimeout(function(){
						$("#postAlert").hide();
            		}, 3000);
					
					
	            	
	            },
					
					    function(returnedData){
	            	
					         console.log(returnedData);
					});
				$scope.MessageId = Mid;
			}
			
	}]);


//(function(){var homeAppMessagesUpdate = angular.module('homeAppMessagesUpdate', []);
//create angular controller
homeApp.controller('MessageUpdate', ['$scope','$http','$sce','$interval','$rootScope',function($scope,$http,$sce,$interval,$rootScope) {
	$rootScope.isAllMessages;
	var that = $scope;
	
	
	 $.post("GetTenLastMessages",
			  {  }
			).then(function(response) {
				$rootScope.TenMessagesArray = JSON.parse(response);
//				$scope.TenMessagesArray = MessagesArray;
				$interval($scope.update, 200,[1]);
				$rootScope.isAllMessages=true;
           },
				
				    function(returnedData){
				         console.log(returnedData);
				});
     
	 $scope.Logout = function(){
   	  
   	  //alert('hi');
   		  $.post("InvalidateUserSession",
   				  { }
   				).then(function(response) {
               	
   					if (response == "Success")
   					{
   						window.location = '\login.html';
   					}
   					else
   					{
   						
           		
   					}
   				},
   				
   				    function(returnedData){
   				         console.log(returnedData);
   					});

     };
     
     $scope.update = function(){
    	 if($rootScope.isAllMessages){
	      $.post("GetTenLastMessages",
				  {  }
				).then(function(response) {
					
					var MessagesArray = JSON.parse(response);
					$rootScope.TenMessagesArray = MessagesArray;
//					$("#messageDesply").html($scope.TenMessagesArray);
//					window.setTimeout($scope.update, 10000);
//					$interval($scope.update, 20000);
	            },
					
					    function(returnedData){
					         console.log(returnedData);
					});
    	 }else{
   	      $.post("GetUserFollowesTenLastMessages",
				  {  }
				).then(function(response) {
					
					var MessagesArray = JSON.parse(response);
					$rootScope.TenMessagesArray = MessagesArray;
//					$("#messageDesply").html($scope.TenMessagesArray);
//					window.setTimeout($scope.update, 10000);
//					$interval($scope.update, 20000);
	            },
					
					    function(returnedData){
					         console.log(returnedData);
					});
    	 }
    	 $interval($scope.update, 20000);
     }
     
     $scope.changemessages = function(value){
    	 $rootScope.isAllMessages=value;
     }
     $scope.follow = function(followeName){
   	  $.post("FollowUser",
   			  { followe :  followeName}
				).then(function(response) {
           	
					if (response == "Success")
					{
						
						$("#successAlert").show();
						setTimeout(function(){
							$("#successAlert").hide();
	            		}, 3000);
           			
					}
					else
					{
					if(response == "alredyExist"){
						
						$("#errorAlert").show();
						setTimeout(function(){
							$("#errorAlert").hide();
	            		}, 3000);
						//alert("You are already following " + followeName);
					}
       		
					}
				},
				
				    function(returnedData){
				         console.log(returnedData);
					});
     }
     
     //this function is responiable for retuning how much time have pased from
     //the publish of the message.
     $scope.getTime = function(string){
   	  var d = new Date(string);
   	  var now = new Date();
   	  var returntext;
   	  var milicesoundsdiff = (now.getTime() - d.getTime());
   	  if((milicesoundsdiff / 1000)< 60){
   		  returntext = (Math.round(milicesoundsdiff / 1000)).toString() +' seconds ago';
   		  return $sce.trustAsHtml(returntext);
   	  }else if((milicesoundsdiff / 60000) < 60){
   		  returntext = (Math.round(milicesoundsdiff / 60000)).toString() +' minutes ago'; 
   		  return $sce.trustAsHtml(returntext);
   	  }else if((milicesoundsdiff / 3600000) < 24){
			  returntext = (Math.round(milicesoundsdiff / 3600000)).toString() +' hours ago'; 
			  return $sce.trustAsHtml(returntext);
   	  }else{
   		  returntext = d.getDate().toString() + '/' +d.getMonth().toString() + '/' + d.getFullYear() + ' at' +d.getHours() + ':' +d.getMinutes();
   		  return $sce.trustAsHtml(returntext);
   	  }
   	  
   	  return d;
     }
     
     $scope.al = function (){
   	  alert('works');
     }
     
     //this function is to turn the returned messages into
     //a html.
     $scope.setcheck = function(text){
   	  
   	  return $sce.trustAsHtml(text);
     }
     
     //this method is for posting a new message
		$scope.AddSubMessage = function(text,isRepublish,messageid){
			//find the place of the topic in the message
			var topicStartIndex = text.indexOf('#');
			var topicEndIndex   = text.indexOf(' ',topicStartIndex);
			var topic;
		
			if(topicStartIndex != -1){  
				//highlight the topic 
				if(topicEndIndex == -1){
					match = text.substring(topicStartIndex,text.length);
				}else{
					match = text.substring(topicStartIndex,topicEndIndex);
				}
		  
				topic = match.substring(1);
			}
			$.post("PostNewMessage",
					{ Topic 	:     topic,
					Content : 	  text }
				).then(function(response) {
					var json = JSON.parse(response);
					//alert(json["Autor"]);
					$("#postAlert").show();
					setTimeout(function(){
						$("#postAlert").hide();
            		}, 3000);
				
         	
				},
				
				    function(returnedData){
         	
				         console.log(returnedData);
					});
				if(isRepublish){
					$.post("IncreaseMessageRepublishNumber",
							{ MessageId 	:     messageid}
						).then(function(response) {
							var json = JSON.parse(response);
							//alert(json["Autor"]);
							$("#postAlert").show();
							setTimeout(function(){
								$("#postAlert").hide();
		            		}, 3000);
						
		         	
						},
						
						    function(returnedData){
		         	
						         console.log(returnedData);
							});
				}
			}
	}]);

homeApp.filter('HomeMessageDate',function(){
	return function(string){
		var d = new Date(string);
	 	  var now = new Date();
	 	  var returntext;
	 	  var milicesoundsdiff = (now.getTime() - d.getTime());
	 	  if((milicesoundsdiff / 1000)< 60){
	 		  returntext = (Math.round(milicesoundsdiff / 1000)).toString() +' seconds ago';
	 		  return returntext;
	 	  }else if((milicesoundsdiff / 60000) < 60){
	 		  returntext = (Math.round(milicesoundsdiff / 60000)).toString() +' minutes ago'; 
	 		  return returntext;
	 	  }else if((milicesoundsdiff / 3600000) < 24){
				  returntext = (Math.round(milicesoundsdiff / 3600000)).toString() +' hours ago'; 
				  return returntext;
	 	  }else{
	 		  returntext = d.toLocaleDateString().replace(".", "/").replace(".", "/") + ' at ' + d.toLocaleTimeString().substring(0, 5);
	 		  return returntext;
	 	  }
	 	  
	 	  return d;
	   }
	
})
})();
